package com.erb.service.zwj.impl;

import com.erb.entity.Pager;
import com.erb.entity.integral;
import com.erb.mapper.SignInRecordMapper;
import com.erb.service.zwj.ISignInRecordService;
import com.erb.utils.DateUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.util.*;

@Transactional(rollbackFor = RuntimeException.class)
@Service("signInRecordService")
public class SignInRecordServiceImpl implements ISignInRecordService {
	DateFormat dateInstance = DateFormat.getDateInstance();
	@Resource
	private SignInRecordMapper signInRecordMapper;

	@Override
	public List<Integer> getSignedInDateOfMonth(int userId, int month) {
		List<Integer> signedInDate;

		List<integral> recordList = this.findIntegralOfMonth(userId, month);
		signedInDate = new ArrayList<>(recordList.size());

		Calendar calendar = Calendar.getInstance();
		for (integral i : recordList) {
			calendar.setTimeInMillis(i.getCreateTime().getTime());

			signedInDate.add(calendar.get(Calendar.DATE));
		}
		return signedInDate;
	}

	@Override
	public List<integral> findIntegralOfMonth(int userId, int month) {
		if (userId > 0) {
			long startTime = DateUtils.getStartTimeOfMonth(month);
			long endTime = DateUtils.getEndTimeOfMonth(month);

			return signInRecordMapper.findIntegralByTimeHorizon(userId, dateInstance.format(new Date(startTime)), dateInstance.format(new Date(endTime)));
		}
		return Collections.emptyList();
	}

	@Override
	public Pager findRecordsOfUser(Pager pager, int userId) {
		// 查询总数
		if (userId > 0) {
			pager.page(this.findCountRecordOfUser(userId));
			pager.setData(signInRecordMapper.findRecordsOfUser(pager, userId));
		} else {
			pager.page(0);
			pager.setData(Collections.emptyList());
		}
		return pager;
	}

	@Override
	public Integer findCountRecordOfUser(int userId) {
		if (userId > 0) {
			return signInRecordMapper.findCountRecordOfUser(userId);
		}
		return 0;
	}
}
